<template>  
    <div>
        <custom-nav-bar :text="'个人中心'" :bgColor="`rgba(121,102,179,${opacity})`" :frontColor="'#ffffff'" :isFixed="true" />
    </div>
  <view class="g-page-box page-my">
    <view class="header">
      <image class="header-bg" src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/my_banner_2x.png"></image>
      <view class="g-flex-row avatar-box">
        <view class="g-flex-row profile">
          <button class="auth-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image v-if="loginS.userInfo?.value?.avatar" :src="loginS.userInfo?.value?.avatar" class="avatar"></image>
            <image v-else src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/default_avatar_2x.png" class="avatar"></image>
            <image src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/edit_icon.png" class="edit-icon"></image>
          </button>
          <view class="username-box">
            <view class="g-fs-32 g-fw-b g-flex-row username" @click="debounceHandleChangeUserName">
              <text class="name">{{ loginS.userInfo?.value?.userName || '新用户' }}</text>
              <image src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/edit_icon_white.png" class="edit-icon"></image>
            </view>
            <view class="phone"> {{ loginS.userInfo.value?.phone ? loginS.userInfo.value.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '未绑定手机' }}</view>
          </view>
        </view>
        <view class="jifen-box">
          <view @click="handlerGotoPoint">
            <view class="g-fs-36 g-fw-b jifen">积分：{{ loginS.userInfo?.value?.points || 0 }}</view>
            <view class="jifen-center">积分中心</view>
          </view>
        </view>
      </view>
    </view>

    <view class="g-pl-24 g-pr-24 page-ct">
      <!-- 运动卡片 -->
      <view class="g-mb-36 g-radius-40 g-bg-white g-card-box card1" @click="handlerSwitchTab">
        <view class="g-flex-row logo-box">
          <view class="g-flex-row">          
            <text class="g-fs-32 g-fw-b logo-title">运动数据</text>
          </view>
          <view class="g-flex-row">
              <text class="see-detail">查看详情</text>
              <image class="logo-order" src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/lft_pointer2x.png"></image>
          </view>
        </view>
        
        <view class="g-flex-row sport-pannel">      
          <view class="g-flex-col">
              <view>
                  <text class="g-fs-40 g-fw-b">{{ myStore.courseNum }}</text>
                  <text class="g-fs-24 dw">次</text>
              </view>
              <view class="g-fs-24 g-color-gray g-mt-10">
                  累计运动次数
              </view>
              <view class="split"></view>
          </view>
          <view class="g-flex-col">
              <view>
                  <text class="g-fs-40 g-fw-b">{{ myStore.totalTime }}</text>
                  <text class="g-fs-24 dw">分钟</text>
              </view>
              <view class="g-fs-24 g-color-gray g-mt-10">
                  累计运动时长
              </view>
              <view class="split"></view>
          </view>
          <view class="g-flex-col">      
              <view>
                  <text class="g-fs-40 g-fw-b">{{ (myStore.totalCle && parseFloat(myStore.totalCle).toFixed()) || 0 }}</text>
                  <text class="g-fs-24 dw">千卡</text>
              </view>
              <view class="g-fs-24 g-color-gray g-mt-10">
                  累计消耗卡路里
              </view>
          </view>
        </view>
      </view>

      <!-- banner0环形操年卡续费,环形操年卡：#F5AE4B； -->
      <banner v-if="showCardFlag" :animate="false" :backgroundColor="cardNameTypeColor" :onClick="handlerClickBanner">
          <view class="g-flex-row card-overdate">
            <view class="g-flex-col lft">
                <view class="g-flex-row name">
                    <image class="nosport-icon" src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/banner001_2x.png"></image>
                    <text class="g-fs-32">{{ loginS.userInfo.value?.memberCard.name }}</text>
                </view>
                <view  class="g-mt-10 g-fs-24 date">有效期: {{ loginS.userInfo.value?.memberCard.effectiveDate || '-' }} 至 {{ loginS.userInfo.value?.memberCard.expirationDate||'-' }}</view>
            </view>
            <view class="rgt">续费</view>
          </view>
          <view class="card-overdate-desc">
            {{ cardDateDiff > 0 ? `您的会员还剩 ${cardDateDiff} 天过期`:'您的会员已经过期'}}
            <text v-if="cardCount">，次卡还剩 {{ cardCount }} 次</text>
          </view>
      </banner>

       <!-- 导航 -->
       <view class="g-mb-36 g-radius-40 g-bg-white g-card-box card-nav-box">
        <view class="g-flex-row justify-between card-nav-item" v-for="(item, index) in myStore.navList" :key="index" @click="hanlderClickNav(item)">
          <view class="g-flex-row">
            <image class="nav-icon" :src="item.icon"></image>
            <span class="nav-title">{{item.text}}</span>
          </view>
          <view class="g-flex-row navdesc-box">
            <text v-if="item.count>0" class="g-fs-24 desc">
              <text class="g-fs-24 counter">{{ item.count }}</text>
              <text class="g-fs-24 g-color-gray">{{ item.desc }}</text>
            </text>
            <image class="logo-order" src="https://andy-res.oss-cn-chengdu.aliyuncs.com/meyka-miniapp/static/lft_pointer2x.png"></image>
          </view>
        </view>
      </view>
    </view>
  </view>
  <!--有效期时间-->
  <popup-view v-model="showChangeUserName" customStyle="background: #ffffff;">
    <view class="customer-date-box">
        <!-- 添加日期时间选择器 -->
        <view class="g-flex-row input-date-box">
            <text class="g-fs-32 f-fw-b">昵称：</text>
            <input 
              ref="nicknameRef" 
              class="input-date"
              type="nickname" 
              :value="nickname"
              @input="fillNickname"
              @focus="handleInputFocus"
              @blur="handleInputBlur"
              placeholder="请输入昵称" 
            />
        </view>
        <view>
            <button class="g-fs-32 neworder-btn" @click="submitUserName">确认</button>
        </view>
    </view>
</popup-view>
</template>
  
<script setup>
import { onMounted, ref } from 'vue';
import { useGlobalStore } from "@/store/gobal";
import { useMyStore } from "@/store/my";
import useLogin from "@/functions/useLogin";
import { onShow, onPageScroll } from "@dcloudio/uni-app";
import { debounce } from '@/utils';
import setTab from '@/functions/useSetTab';
import dayjs from 'dayjs';
import { GUO_QI_DAY } from '@/config/index';

const globalStore = useGlobalStore();
const myStore = useMyStore();
const userAvatar = ref('');
const loginS = useLogin();
const showChangeUserName = ref(false);
const nicknameRef = ref(null);
const nickname = ref('');
const isInputting = ref(false);


// 展示过期卡片
const showCardFlag = ref(false);
const cardNameTypeColor = ref('#7966B3');
const cardDateDiff = ref(0);
const cardCount = ref(0);

const handlerSwitchTab = () => {
  // uniapp 切换tab
  uni.switchTab({
      url: "/pages/sport/index",
  });
};

/**
 * 自动填充昵称
 *
 * @param e 事件对象，包含输入框的值和状态
 */
const fillNickname = (e) => {
  console.log('fillNickname', e.detail.value);
  console.log(isInputting.value);
  // todo:自动更新昵称
  if(isInputting.value){
    nickname.value = e.detail.value || '';
  }else if(e.detail.value === ''){
    // 如果输入框失去焦点且内容为空，这里可以选择不更新昵称，或者恢复为某个默认值
    // 例如，可以选择不做任何操作，保留原昵称
  } else {
    // 如果输入框失去焦点且内容不为空，可以选择更新昵称
    nickname.value = e.detail.value;
  }
};


/**
 * 处理输入框获取焦点的事件
 *
 * 当输入框获取焦点时，将isInputting的值为true
 */
const handleInputFocus = () => {
  isInputting.value = true;
};

const handlerGotoPoint = () => {
  uni.navigateTo({
    url: '/pages/point/index',
  });
};


/**
 * 处理输入框失去焦点事件
 *
 * 当输入框失去焦点时，将 isInputting 的值设置为 false
 */
const handleInputBlur = () => {
  isInputting.value = false;
};

const handlerClickBanner = () => {
  console.log('handlerClickBanner');
  uni.navigateTo({
    url: '/pages/my/card/index',
  });
};

/**
 * 异步函数，用于提交用户名
 *
 * @returns 无返回值
 */
const submitUserName = async () => {
  console.log('submitUserName', nickname.value);
  const res = await myStore.updateNickName(nickname.value);
  if (res && res.status === 200) {
    showChangeUserName.value = false;
    loginS.userInfo.value.userName = nickname.value;
    uni.showToast({
      title: '昵称修改成功',
      icon: 'success'
    });
    console.log('loginS', loginS);
  } else {
    uni.showToast({
      title: '昵称修改失败',
      icon: 'none'
    });
  }
};


// 滚动事件 接入自定义头部导航
const opacity = ref(0);
const scrollTop = ref(0);
onPageScroll(data => {
  // 保存scrollTop值，用于后续计算滚动距离
  scrollTop.value = data.scrollTop || 0;

  if (data.scrollTop < 10) {
    opacity.value = 0;
  } else if (data.scrollTop >= 10 && data.scrollTop <= 50) {
    opacity.value = (data.scrollTop - 10) / 10;
  } else if (data.scrollTop > 50) {
    opacity.value = 1;
  }
});

/**
 * 处理更改用户名的操作
 *
 * @returns 无返回值
 */
const handleChangeUserName = () => {
  showChangeUserName.value = true;
}
const debounceHandleChangeUserName = debounce(handleChangeUserName, 300);

const hanlderClickNav = (item) => {
  console.log('hanlderClickNav', item);
  switch (item.href) {
    case "courseorder":
      uni.navigateTo({
        url: '/pages/my/courseorder/index',
      });
      break;
    case "card":
      uni.navigateTo({
        url: '/pages/my/card/index',
      });
      break;
    case "order":
      uni.navigateTo({
        url: '/pages/my/order/index',
      });
      break;
    default:
      if (globalStore.phoneNumber) {
        uni.makePhoneCall({
          phoneNumber: globalStore.phoneNumber,
        });
      }
      break;
  }
};

const base64ToBlob = (base64, type = 'image/png') => {
  // 转换 Base64 为二进制数据
  const arrayBuffer = uni.base64ToArrayBuffer(base64);

  // 创建 Blob 对象
  return new Blob([arrayBuffer], { type });
};

const handleGetUserInfo = async (e) => {
  uni.getUserProfile({
    desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      uni.downloadFile({
        url: res?.userInfo?.avatarUrl,
        success:function(downRes){
          uni.getFileSystemManager().readFile({
            filePath: downRes.tempFilePath,
            encoding: 'base64',
            success: (base64Res) => {
              uni.getImageInfo({
                src: res.userInfo.avatarUrl,
                success: (infoRes) => {
                  var type = infoRes.type;
                  var tempBase64 = 'data:image/' + type + ';base64,' + base64Res.data;
                  loginS.updateUserInfo(null, tempBase64, null).then((updateRes) => {
                      if(updateRes && updateRes.status === 200) {
                        loginS.userInfo.value.avatar = res?.userInfo?.avatarUrl;
                        // 修改头像成功
                        uni.showToast({
                          title: '头像更新成功！',
                          icon: 'success'
                        });
                      }
                  }).catch((err) => {
                    uni.showToast({
                      title: '1头像更新失败！',
                      icon: 'none'
                    });
                  });
                },
                fail: () => {
                  uni.showToast({
                    title: '2头像更新失败！',
                    icon: 'none'
                  });
                }
              });
            },
            fail:()=>{
              uni.showToast({
                title: '3头像更新失败！',
                icon: 'none'
              });
            }
          })
        },
        fail: (err) => {
          console.error('下载头像失败:', err);
          uni.showToast({
            title: '头像更新失败！',
            icon: 'none'
          });
        }
      })
    },
    fail: (err) => {
      console.error('用户拒绝授权:', err);
      uni.showToast({
        title: '授权失败，请在设置中开启权限！',
        icon: 'none'
      });
    }
  });
}

/**
 * 判断日期是否已过期
 * @param date 目标日期（格式：YYYY-MM-DD）
 * @returns 是否过期（true/false）
 */
 const isOverdue = (date) => {
  const now = dayjs(); // 当前时间
  const expireTime = dayjs(date).endOf('day'); // 目标日期的 23:59:59
  return expireTime.diff(now, 'day') <= GUO_QI_DAY;
};

const setCardNameType = (card) => {
  console.log('card', card);
  if(card && card.name && card.name.indexOf('半年卡')>-1){
    cardNameTypeColor.value = '#E5A096';
  } else if(card && card.name &&  card.name.indexOf('年卡') > -1) {
    cardNameTypeColor.value = '#F5AE4B';
  }else if(card && card.name && card.name.indexOf('月卡') > -1) {
    cardNameTypeColor.value = '#7966B3';
  }
  showCardFlag.value = true;
};

const onChooseAvatar = (e) => {
  //e.detail.avatarUrl就是用户选择的头像本地路径    
  console.log(e.detail.avatarUrl)
  var imgUrl = e.detail.avatarUrl || "";
  var typeary = imgUrl.split(".");
  var type = typeary.length >= 2 ? typeary[1] : "png";
  console.log(type);
  uni.getFileSystemManager().readFile({
    filePath: imgUrl,
    encoding: 'base64',
    success: res => {
      var tempBase64 = 'data:image/' + type + ';base64,' + res.data;
      loginS.updateUserInfo(null, tempBase64, null).then((updateRes) => {
          if(updateRes && updateRes.status === 200) {
            loginS.userInfo.value.avatar = updateRes?.data?.userDetails?.avatar||'';
            // 修改头像成功
            uni.showToast({
              title: '头像更新成功！',
              icon: 'success'
            });
          }
      }).catch((err) => {
        uni.showToast({
          title: '头像更新失败！',
          icon: 'none'
        });
      });
    }
  })
};

/**
 * 计算两个日期相差的天数
 * @param date 目标日期（格式：YYYY-MM-DD）
 * @returns 相差的天数
 */
 const getDayDiff = (date) => {
  const today = dayjs().startOf('day'); // 获取当天的 00:00:00
  const targetDate = dayjs(date).startOf('day'); // 目标日期的 00:00:00
  const diffDayCount = targetDate.diff(today, 'day');
  return diffDayCount < 0 ? 0 : diffDayCount;
};
  
onShow(async () => {
  // 切换默认tab 底部
  setTab(3);
    // 判断登录，并不会自动跳转
  const flag = await loginS.checkLogin();
  console.log('checkLogin', flag);

  console.log('userInfo', loginS?.userInfo);
  console.log(loginS?.userInfo?.phone);
  console.log(globalStore.phoneNumber);
  if (flag) {
    myStore.init(loginS.userInfo.value?.userId);

    // 判断是否出弹层
    if (loginS.userInfo.value?.memberCard && loginS.userInfo.value?.memberCard.status === '2') {
      // 先判断会员是否过期，过期了就弹出弹层
      setCardNameType(loginS.userInfo.value?.memberCard);
    } else if (loginS.userInfo.value?.memberCard && loginS.userInfo.value?.memberCard.status === '1' && isOverdue(loginS.userInfo.value?.memberCard.expirationDate)) {
      // 会员卡即将过期，弹出续费弹层
      cardDateDiff.value = getDayDiff(loginS.userInfo.value?.memberCard.expirationDate);
      cardCount.value = loginS.userInfo.value?.timeCard?.remainingSessions || 0;
      setCardNameType(loginS.userInfo.value?.memberCard);
    }
  }
});
</script>
  
<style  scoped lang="scss">
  ::v-deep .mask{
    z-index: 50!important;
  }
  ::v-deep .popup-view-content{
    z-index: 100!important;
  }
  // 弹窗样式
  .customer-date-box{
      padding:40rpx 52rpx 160rpx 52rpx;
      .input-date-box{
          padding-bottom:48rpx;
          .input-date{
              flex: 1;
              background: #F0F3F7;
              border-radius: 12rpx;
              height: 80rpx;
              line-height: 80rpx;
              padding-left:30rpx;
              padding-right:30rpx;
          }
      }
      .xieyi-box{
          padding-bottom: 32rpx;
          font-size: 28rpx;
          .checkbox{
              margin-right: 20rpx;
          }
          .color-blue{
              margin-left:10rpx;
              color:#428DFF;
              text-decoration: underline;
          }
      }
      .neworder-btn{
          height: 88rpx;
          background: #7966B3;
          color:#fff;
          line-height: 88rpx;
      }
  }
  // 页面整体样式
  .page-my{
    .header{
      position: relative;
      z-index: 0;
      &-bg{
        width: 100%;
        height:560rpx;
      }
      &-title{
        font-weight: 600;
        font-size: 36rpx;
        position: absolute;
        top: 408rpx;
        left: 24rpx;
        color:$uni-bg-color;
      }
      .avatar-box{
        position: absolute;
        top:212rpx;
        justify-content: space-between;
        width:100%;
        padding-left:24rpx;
        padding-right:24rpx;
        box-sizing: border-box;
        .auth-btn{
          padding: 0rpx;
          margin: 0rpx;
          background: transparent;
          line-height: 0rpx;
          position: relative;
          &::after{
            border:0rpx;
          }
          .edit-icon{
            width:30rpx;
            height:30rpx;
            position: absolute;
            top:5rpx;
            right:5rpx;
            padding:6rpx;
            border-radius: 50%;
            border:2px solid #fff;
            background:  #F1F1F1;
          }
        }
        .username-box{
          color:#fdfdfe;
          margin-left:25rpx;
          .phone{
            color:#e1ddeb;
            margin-top:20rpx;
          }
          .username{
            .name{
              max-width: 200rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          .edit-icon{
            width:30rpx;
            height:30rpx;
            margin-left:10rpx;
          }
        }
        .avatar {
          width: 160rpx; /* 设置头像宽度 */
          height: 160rpx; /* 设置头像高度，与宽度相等以确保为正方形 */
          border-radius: 50%; /* 圆形效果 */
          border: 2px solid #fff; /* 可选：添加边框 */
          object-fit: cover; /* 确保图片内容适应容器 */
          background-color: #F1F1F1; /* 可选：添加背景颜色 */
        }
        .jifen-box{
          border-radius: 20rpx 20rpx 40rpx 40rpx;
          width:262rpx;
          height: 170rpx;
          background:#998ab2;
          display: flex;
          justify-content: center;
          align-items: center;
          color:#fdfdfe;
          .jifen-center{
            border-radius: 12rpx 12rpx 24rpx 24rpx;
            width:220rpx;
            height:60rpx;
            line-height: 60rpx;
            text-align: center;
            background: #7966b3;
            color:#fdfdfe;
            margin-top:20rpx;
          }
        }
      }
    }
    .page-ct{
      position: relative;
      margin-top:-110rpx;
      z-index: 5;
      padding-bottom:104rpx;
      .card1{
        padding:0rpx;
        .logo-box{
          justify-content: space-between;
          padding-top:24rpx;
          padding-left:20rpx;
          padding-right:20rpx;
          .logo-bg{
            width: 76rpx;
            height: 76rpx;
          }
          .logo-title{
            margin-left:16rpx;
            color:#333;
          }
          .logo-order{
            width: 48rpx;
            height: 48rpx;
          }
        }
        .sport-pannel{
          padding:40rpx 20rpx;
          .g-flex-col{
            flex:1;
            position:relative;
            .dw{
                padding-left:5rpx;
            }
          }
          .split{
            position:absolute;
            right:0rpx;
            width:0rpx;
            border-right:2rpx solid #979797;
            top:50%;
            height:48rpx;
            margin-top:-24rpx;
          }
        }
        .sport-times{
          border-radius: 0rpx 0rpx 40rpx 40rpx;
          justify-content: space-between;
          padding-top:18rpx;
          padding-bottom:18rpx;
          .section-value{
            color:#333;
            padding-right:8rpx;
          }
          .order-course{
            margin:0rpx;
            margin-right:32rpx;
            width: 220rpx;
            height: 72rpx;
            line-height: 72rpx;
            background: #7966B3;
            border-radius: 12rpx 12rpx 28rpx 12rpx;
            font-size:32rpx;
            color:#fff;
          }
          .nosport-box{
            display: flex;
            justify-content: center;
            .nosport-icon{
              width: 40rpx;
              height: 40rpx;
              margin-right:5rpx;
            }
          }
        }
      }
      
      .card-overdate{
        justify-content: space-between;
        color:#fff;
        .lft{
            align-items: self-start;
            .date{
                color: rgba(255,255,255,0.8);
            }
            image{
                width: 60rpx;
                height: 36rpx;
                margin-right: 6rpx;
            }
        }
        .rgt{
            width:156rpx;
            height:72rpx;
            line-height:72rpx;
            text-align:center;
            background:rgba(0,0,0,.2);
            border-radius:12rpx;
        }
      }
    }
    .card-overdate-desc{
      margin-top:20rpx;
      border-top:1px dashed rgba(255,255,255,0.2);
      padding-top:15rpx;
      color:#fff;
    }

    .justify-between{
      justify-content: space-between;
    }

    .card-nav-box{
      .nav-icon{
        width:44rpx;
        height: 44rpx;
      }
      .logo-order{
        width: 48rpx;
        height: 48rpx;
      }
      .card-nav-item{
        padding-top:24rpx;
        padding-bottom:24rpx;
        .nav-title{
          margin-left:20rpx;
        }
        .counter{
          padding-left:3px;
          padding-right:3px;
        }
      }
    }
  }
</style>
  